// miniprogram/pages/myGroup/myGroup.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    groups: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    } else {
      this.loadMyGroups()
    }
  },
  onShow () {
    if (app.globalData.userInfo) {
      this.loadMyGroups()
    }
  },

  async loadMyGroups (noLoading) {
    if (!noLoading) {
      wx.showLoading({
        title: '学习组加载中...'
      })
    }
    const { result } = await wx.cloud.callFunction({
      name: 'loadMyGroups',
      data: {}
    })
    this.setData({
      groups: result
    })
    if (!noLoading) {
      wx.hideLoading()
    }
  },
  // 退出学习组
  async handleExit (e) {
    const exit = await wx.showModal({
      title: '警告',
      content: '确定退出学习组吗？'
    })
    if (exit.cancel) {
      wx.showToast({
        title: '取消退出',
        icon: 'none'
      })
    } else if (exit.confirm) {
      wx.showLoading({
        title: '退出中...'
      })
      const group = e.currentTarget.dataset.groupInfo
      const { result } = await wx.cloud.callFunction({
        name: 'exitGroup',
        data: group
      })
      if (result.status === 0) {
        wx.showToast({
          title: result.msg,
          icon: 'success'
        })
        this.loadMyGroups(true)
        const newUserGroups = app.globalData.userInfo.groups.filter(item => item.groupId !== group.groupId)
        app.globalData.userInfo.groups = newUserGroups
      } else {
        wx.hideLoading()
      }
    }
  }
})